<template>
  <basic-container>
    <div>
      <m-s-search
        @searchClick="
          (v) => {
            (queryForm = v), getList();
          }
        "
        :list="taskConfigOption.column"
      >
      </m-s-search>
    </div>

    <avue-crud
      :option="taskConfigOption"
      :data="data"
      :table-loading="loading"
      :page.sync="page"
      @current-change="currentChange"
      @size-change="sizeChange"
      @selection-change="(v) => (selection = v)"
      ref="curd"
    >
      <template slot="menuLeft">
        <el-button
          size="small"
          type="primary"
          @click="addToTabsList('任务', { oid: -1 }, 'taskConfigTemp', 'open')"
          >新增
        </el-button>
      </template>
      <template slot="scheduleType" slot-scope="{ row }">
        <div>{{ row.scheduleType }}:{{ row.scheduleConf }}</div>
      </template>
      <template slot="glueType" slot-scope="{ row }">
        <div>{{ row.glueType }}:{{ row.executorHandler }}</div>
      </template>
      <template slot="triggerStatus" slot-scope="{ row }">
        <div>
          <el-tag v-if="row.triggerStatus === 1">RUNNING</el-tag>
          <el-tag type="info" v-if="row.triggerStatus === 0">STOP</el-tag>
        </div>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-dropdown>
          <el-button size="mini" type="text"
            >操作<i class="el-icon-arrow-down el-icon--right"></i
          ></el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click.native="triggerJob(row, 'trigger')"
                >执行一次</el-dropdown-item
              >
              <el-dropdown-item @click.native="searchLog(row)"
                >查询日志</el-dropdown-item
              >
              <el-dropdown-item @click.native="triggerJob(row, 'registerNode')"
                >注册节点</el-dropdown-item
              >
              <el-dropdown-item @click.native="triggerJob(row, 'nextTime')"
                >下次执行时间</el-dropdown-item
              >
              <el-divider />
              <el-dropdown-item
                @click.native="startJob(row)"
                v-if="row.triggerStatus === 0"
                >启动</el-dropdown-item
              >
              <el-dropdown-item
                @click.native="stopJob(row)"
                v-if="row.triggerStatus === 1"
                >停止</el-dropdown-item
              >
              <el-dropdown-item
                @click.native="
                  addToTabsList('任务', row, 'taskConfigTemp', 'edit')
                "
                >编辑</el-dropdown-item
              >
              <el-dropdown-item @click.native="removeJob(row)"
                >删除</el-dropdown-item
              >
              <el-dropdown-item
                @click.native="
                  addToTabsList('任务', row, 'taskConfigTemp', 'open')
                "
                >复制</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </avue-crud>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="triggerVisible"
      :width="dialogWidth"
      append-to-body
    >
      <div v-if="dialogType === 'trigger'" :key="randomKey">
        <el-form :model="form" ref="triggerForm">
          <el-form-item label="执行参数" :label-width="formLabelWidth" props="">
            <el-col :span="20">
              <code-editor
                :mode="'javascript'"
                v-model="form.executorParam"
                ref="ecEditor"
              ></code-editor>
              <!-- <el-input v-model="form.executorParam" type="textarea"></el-input> -->
            </el-col>
          </el-form-item>
          <el-form-item label="机器地址" :label-width="formLabelWidth">
            <el-col :span="20">
              <el-input
                v-model="form.addressList"
                t
                v-if="dialogType === 'trigger'"
                type="textarea"
              ></el-input>
            </el-col>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="dialogType === 'registerNode'">1.注册节点</div>
      <div v-if="dialogType === 'nextTime'">
        <div v-for="item in nextExecuteTime" :key="item" class="nextTimeItem">
          {{ item }}
        </div>
      </div>
      <div slot="footer" class="dialog-footer" v-if="dialogType === 'trigger'">
        <el-button @click="triggerVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmTrigger">确 定</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button @click="triggerVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <ms-drawer
      @refresh="getList()"
      :visible.sync="visible"
      :tab-list.sync="tabsList"
    ></ms-drawer>
  </basic-container>
</template>

<script>
import MSSearch from "@/DMDComponents/MSSearch.vue";
import * as taskManageApi from "@/api/taskManage/taskManage";
import CodeEditor from "@/components/code-editor/index";

export default {
  name: "taskConfig",
  components: {
    MSSearch,
    CodeEditor,
  },
  inject: ["taskConfigOption"],

  data() {
    return {
      form: {
        executorParam: "",
        addressList: "",
      },
      formLabelWidth: 100,
      triggerVisible: false,
      data: [],
      queryForm: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 1,
      },
      visible: false,
      loading: false,
      tabsList: [],
      randomKey:100,
      rules: {
        executorParam: [
          { required: true, message: "请输入任务参数", trigger: "blur" },
        ],
        addressList: [
          { required: true, message: "请输入机器地址", trigger: "blur" },
        ],
      },
      currentData: {},
      dialogTitle: "",
      dialogWidth: 400,
      dialogType: "",
      titleObj: {
        trigger: "执行一次",
        registerNode: "注册节点",
        nextTime: "下次执行时间",
      },
      nextExecuteTime: [],
    };
  },
  methods: {
    startJob(data) {
      this.$confirm("确定启动？").then(() => {
        try {
          taskManageApi.startJob({ id: data.id }).then(() => {
            this.$message.success("启动成功");
            this.getList();
          });
        } catch (err) {}
      });
    },
    stopJob(data) {
      this.$confirm("确定停止？").then(() => {
        try {
          taskManageApi.stopJob({ id: data.id }).then(() => {
            this.$message.success("停止成功");
            this.getList();
          });
        } catch (err) {}
      });
    },
    removeJob(data) {
      this.$confirm("确定删除？").then(() => {
        taskManageApi.removeJob({ id: data.id }).then(() => {
          this.$message.success("删除成功");
          this.getList();
        });
      });
    },
    searchLog(row) {
      this.$router.push({
        path: "/taskManage/dispatchLog",
        query: {
          jobGroup: this.queryForm.jobGroup,
          jobId: row.id,
        },
      });
    },
    confirmTrigger() {
      const paramData = {
        ...this.form,
        id: this.currentData.id,
      };
      if (this.form.executorParam) {
        try {
          const executorParam = JSON.parse(this.form.executorParam);
        } catch (err) {
          this.$message.error("请输入正确的JSON格式");
          return;
        }
      }
      taskManageApi.triggerJob({ ...paramData }).then((res) => {
        this.$message("执行一次成功");
        this.currentData = {};
        this.triggerVisible = false;
      });
    },
    triggerJob(row, type) {
      this.currentData = { ...row };
      this.dialogTitle = this.titleObj[type];
      this.dialogWidth = type === "trigger" ? 400 : 300;
      this.dialogType = type;
      this.triggerVisible = true;
      this.form = {
        ...this.form,
        addressList:'',
        executorParam: row.executorParam || '',
      };
      this.randomKey = Math.floor(Math.random()*100+1);
      if (type === "nextTime") {
        const { scheduleType, scheduleConf } = row;
        taskManageApi
          .nextTriggerTimeJob({ scheduleType, scheduleConf })
          .then((res) => {
            this.nextExecuteTime = res.data.content;
            this.form = {
              executorParam: "",
              addressList: "",
            };
          });
      }
    },
    // 向抽屉中添加tab页 根据 oid 去重
    addToTabsList(title, row, component, type) {
      let ids = this.tabsList.map((item) => item.row[this.idKey]);
      if (!ids.includes(row[this.idKey])) {
        this.tabsList.push({ title, row, component, type });
      }
      this.visible = true;
    },
    getList() {
      const params = {};
      for (let key in this.queryForm) {
        if (this.queryForm[key]) {
          params[key] = this.queryForm[key];
        }
      }
      taskManageApi
        .getJobList({
          ...params,
          start: this.page.currentPage,
          length: this.page.pageSize,
        })
        .then((res) => {
          this.data = res.data.data;
          this.page.total = res.data.recordsTotal;
        });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.getList();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList();
    },
  },
  mounted() {
    this.getList();
  },
};
</script>
<style lang="scss" scoped>
.nextTimeItem {
  padding: 10px;
  text-align: center;
}
</style>
